package com.aizuda.boot.modules.business.negotiation.service.impl;

import com.aizuda.boot.modules.business.contract.dto.SingleResponse;
import com.aizuda.boot.modules.business.contract.dto.UserInfo;
import com.aizuda.boot.modules.business.contract.entity.ContractTypeEntity;
import com.aizuda.boot.modules.common.constant.enums.ResponseCodeEnum;
import com.aizuda.boot.modules.business.contract.util.AuthUtil;
import com.aizuda.boot.modules.business.filling.domain.request.PageQuery;
import com.aizuda.boot.modules.business.negotiation.entity.ContractNegotiationConfigEntity;
import com.aizuda.boot.modules.business.negotiation.entity.ContractNegotiationConfigType;
import com.aizuda.boot.modules.business.negotiation.entity.dto.NegotiationConfigSaveDTO;
import com.aizuda.boot.modules.business.negotiation.entity.dto.NegotiationConfigUpdateDTO;
import com.aizuda.boot.modules.business.negotiation.entity.vo.NegotiationConfigShowDTO;
import com.aizuda.boot.modules.business.negotiation.entity.vo.NegotiationShowListDTO;
import com.aizuda.boot.modules.business.negotiation.mapper.ContractNegotiationConfigMapper;
import com.aizuda.boot.modules.business.negotiation.mapper.ContractNegotiationConfigTypeMapper;
import com.aizuda.boot.modules.business.negotiation.mapper.ContractNegotiationDepartmentMapper;
import com.aizuda.boot.modules.business.negotiation.service.ContractNegotiationConfigService;
import com.aizuda.boot.modules.business.performance.mapper.ContractTypeMapper;
import com.aizuda.boot.modules.system.mapper.SysDepartmentMapper;
import com.aizuda.boot.modules.system.service.ISysUserDepartmentService;
import com.aizuda.bpm.engine.entity.FlwProcess;
import com.aizuda.bpm.mybatisplus.mapper.FlwProcessMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author sangyirong
 * @ClassName ContractNegotiationConfigServiceImpl
 * @Version 1.0
 * @Date 2025/6/28 15:05
 */
@Service
@Slf4j
public class ContractNegotiationConfigServiceImpl extends ServiceImpl<ContractNegotiationConfigMapper, ContractNegotiationConfigEntity> implements ContractNegotiationConfigService {

    @Resource
    private ContractNegotiationConfigTypeMapper contractNegotiationConfigTypeMapper;

    @Resource
    private FlwProcessMapper flwProcessMapper;

    @Resource
    private ContractTypeMapper contractTypeMapper;

    @Resource
    private ContractNegotiationDepartmentMapper contractNegotiationDepartmentMapper;

    @Resource
    private SysDepartmentMapper sysDepartmentMapper;

    @Resource
    private ISysUserDepartmentService sysUserDepartmentService;

    @Override
    public SingleResponse<IPage<NegotiationShowListDTO>> getNegotiationShowList(PageQuery query) {
        // 参数校验
        if (null == query || null == query.getPageNo() || null == query.getPageSize()) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), "分页参数不能为空");
        }
        IPage<ContractNegotiationConfigEntity> page = new Page<>(query.getPageNo(), query.getPageSize());

        IPage<NegotiationShowListDTO> resultPage = new Page<>();
        // 查询协商配置，按优先级降序排序
        LambdaQueryWrapper<ContractNegotiationConfigEntity> queryWrapper = new LambdaQueryWrapper<>();

//        if (AuthUtil.isSuperAdmin()) {
//            // 超级管理员不做限制
//        } else {
//            // 修改逻辑：优先使用当前租户，如果为空则使用租户列表
//            UserInfo currentUser = AuthUtil.getCurrentUser();
//            String currentSysTenantKey = currentUser != null ? currentUser.getSysTenantKey() : null;
//
//            if (currentSysTenantKey != null && !currentSysTenantKey.trim().isEmpty()) {
//                // 如果当前用户有明确的sysTenantKey，只查询该租户下的数据
//                queryWrapper.eq(ContractNegotiationConfigEntity::getSysTenantKey, currentSysTenantKey);
//            } else {
//                // 如果sysTenantKey为null或空，使用原有逻辑（查询用户有权限的所有租户）
//                List<String> userTenantKeys = AuthUtil.getUserTenantKeys();
//                if (userTenantKeys != null && !userTenantKeys.isEmpty()) {
//                    queryWrapper.in(ContractNegotiationConfigEntity::getSysTenantKey, userTenantKeys);
//                } else if (userTenantKeys != null) {
//                    // 空列表表示没有任何租户权限
//                    queryWrapper.eq(ContractNegotiationConfigEntity::getSysTenantKey, "NO_PERMISSION");
//                }
//            }
//        }
        queryWrapper.orderByDesc(ContractNegotiationConfigEntity::getPriority);
        page = this.page(page, queryWrapper);
        if (page.getRecords().isEmpty()) {
            return SingleResponse.of(resultPage);
        }
        List<ContractNegotiationConfigEntity> records = page.getRecords();
//        // 获取租户关联
//        List<String> sysTenantKeys = records.stream().map(ContractNegotiationConfigEntity::getSysTenantKey).toList();
//        Map<String, String> tenantNameMap = sysDepartmentMapper.selectList(Wrappers.<SysDepartment>lambdaQuery()
//                        .in(SysDepartment::getSysTenantKey, sysTenantKeys)
//                        .and(wrapper -> wrapper
//                                .eq(SysDepartment::getPid, 0L)
//                                .or()
//                                .eq(SysDepartment::getIndependentFlag, 1))
//                        .select(SysDepartment::getName, SysDepartment::getSysTenantKey))
//                .stream().collect(Collectors.toMap(SysDepartment::getSysTenantKey, SysDepartment::getName));
        // 获取协商配置全部关联合同类型
        List<Long> negotiationConfigIds = records.stream()
                .filter(Objects::nonNull)
                .map(ContractNegotiationConfigEntity::getId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(negotiationConfigIds)){
            return SingleResponse.of(new Page<>());
        }
        List<ContractNegotiationConfigType> configTypes = contractNegotiationConfigTypeMapper.selectList(
                new LambdaQueryWrapper<ContractNegotiationConfigType>()
                        .in(ContractNegotiationConfigType::getNegotiationConfigId, negotiationConfigIds));
        List<Integer> typeIds = configTypes.stream()
                .filter(Objects::nonNull)
                .map(ContractNegotiationConfigType::getContractTypeId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
        // 查询全部关联合同类型
        List<ContractTypeEntity> typeEntities = new ArrayList<>();
        if (!CollectionUtils.isEmpty(typeIds)) {
            typeEntities = contractTypeMapper.selectList(new LambdaQueryWrapper<ContractTypeEntity>()
                    .in(ContractTypeEntity::getId, typeIds)
                    .select(ContractTypeEntity::getId, ContractTypeEntity::getTypeName));
        }
        // 构建协商合同类型映射
        Map<Long, List<ContractNegotiationConfigType>> map = configTypes.stream()
                .filter(Objects::nonNull)
                .filter(ct -> ct.getNegotiationConfigId() != null)
                .collect(Collectors.groupingBy(ContractNegotiationConfigType::getNegotiationConfigId));
        // 构建合同类型映射
        Map<Integer, String> typeMap = typeEntities.stream()
                .filter(Objects::nonNull)
                .filter(entity -> entity.getId() != null && entity.getTypeName() != null)
                .collect(Collectors.toMap(ContractTypeEntity::getId, ContractTypeEntity::getTypeName));
        // 查询协商关联流程
        List<String> processKeys = records.stream()
                .filter(Objects::nonNull)
                .map(ContractNegotiationConfigEntity::getProcessKey)
                .filter(Objects::nonNull)
                .filter(key -> !key.trim().isEmpty())
                .distinct()
                .collect(Collectors.toList());
        // 查询全部关联流程定义
        Map<String, FlwProcess> processMap = new java.util.HashMap<>();
        if (!CollectionUtils.isEmpty(processKeys)) {
            processMap = flwProcessMapper.selectList(new LambdaQueryWrapper<FlwProcess>()
                            .in(FlwProcess::getProcessKey, processKeys)
                            .select(FlwProcess::getId, FlwProcess::getProcessKey, FlwProcess::getProcessName, FlwProcess::getProcessVersion))
                    .stream()
                    .filter(Objects::nonNull)
                    .filter(process -> process.getProcessKey() != null)
                    .collect(Collectors.groupingBy(FlwProcess::getProcessKey))
                    .values()
                    .stream()
                    .map(processes -> processes.stream()
                            .filter(Objects::nonNull)
                            .max(Comparator.comparing(FlwProcess::getProcessVersion))
                            .orElse(null))
                    .filter(Objects::nonNull)
                    .filter(process -> process.getProcessKey() != null)
                    .collect(Collectors.toMap(FlwProcess::getProcessKey, flw -> flw));
        }
//        // 获取协商定义关联部门
//        List<ContractNegotiationDepartment> negotiationDepartments = contractNegotiationDepartmentMapper.selectList(new LambdaQueryWrapper<ContractNegotiationDepartment>()
//                .in(ContractNegotiationDepartment::getNegotiationConfigId, negotiationConfigIds));
//        List<Long> departmentIds = negotiationDepartments.stream().map(ContractNegotiationDepartment::getDepartmentId).distinct().collect(Collectors.toList());
//
//        Map<Long, List<ContractNegotiationDepartment>> negotiationConfigDepartmentsMap = negotiationDepartments.stream().collect(Collectors.groupingBy(ContractNegotiationDepartment::getNegotiationConfigId));
//
//        Map<Long, String> departmentMap = new java.util.HashMap<>();
//        if (!CollectionUtils.isEmpty(departmentIds)) {
//            departmentMap = sysDepartmentMapper.selectList(new LambdaQueryWrapper<SysDepartment>()
//                            .in(SysDepartment::getId, departmentIds.stream().distinct().collect(Collectors.toList()))
//                            .select(SysDepartment::getId, SysDepartment::getName))
//                    .stream().collect(Collectors.toMap(SysDepartment::getId, SysDepartment::getName));
//        }
        // 构建结果
        ArrayList<NegotiationShowListDTO> result = new ArrayList<>();
        for (ContractNegotiationConfigEntity record : records) {
            // 添加判空处理
            if (record == null) {
                continue;
            }
            
            NegotiationShowListDTO negotiationShowListDTO = new NegotiationShowListDTO();
            negotiationShowListDTO.setId(record.getId());
            negotiationShowListDTO.setNegotiationName(record.getNegotiationName());
            
            // 安全处理流程相关信息
            String processKey = record.getProcessKey();
            if (processKey != null && processMap.containsKey(processKey)) {
                FlwProcess process = processMap.get(processKey);
                if (process != null) {
                    negotiationShowListDTO.setProcessId(process.getId());
                    negotiationShowListDTO.setProcessName(process.getProcessName());
                }
            }
            negotiationShowListDTO.setProcessKey(processKey);
            negotiationShowListDTO.setIsEnabled(record.getIsEnabled());
            negotiationShowListDTO.setIsPublished(record.getIsPublished());
            negotiationShowListDTO.setPriority(record.getPriority()); // 添加优先级字段
            negotiationShowListDTO.setUpdateTime(record.getUpdateTime());
//            negotiationShowListDTO.setSysTenantKey(record.getSysTenantKey());
//            negotiationShowListDTO.setTenantName(tenantNameMap.get(record.getSysTenantKey()));
            
            // 安全处理类型范围信息
            Long recordId = record.getId();
            if (recordId != null && map.containsKey(recordId)) {
                List<ContractNegotiationConfigType> types = map.get(recordId);
                if (types != null && !types.isEmpty()) {
                    List<String> typeName = types.stream()
                            .filter(Objects::nonNull)
                            .map(ContractNegotiationConfigType::getContractTypeId)
                            .filter(Objects::nonNull)
                            .map(typeMap::get)
                            .filter(Objects::nonNull)
                            .collect(Collectors.toList());
                    negotiationShowListDTO.setScope(typeName);
                }
            }
//            if (negotiationConfigDepartmentsMap.containsKey(record.getId())) {
//                List<ContractNegotiationDepartment> departments = negotiationConfigDepartmentsMap.get(record.getId());
//                List<String> departmentName = departments.stream().map(ContractNegotiationDepartment::getDepartmentId).map(departmentMap::get).collect(Collectors.toList());
//                negotiationShowListDTO.setDepartment(departmentName);
//            }
            result.add(negotiationShowListDTO);

        }
        // 构造结果
        resultPage.setRecords(result);
        resultPage.setTotal(page.getTotal());
        resultPage.setCurrent(page.getCurrent());
        resultPage.setSize(page.getSize());
        // 返回结果
        return SingleResponse.of(resultPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SingleResponse<NegotiationConfigShowDTO> saveNegotiationConfig(NegotiationConfigSaveDTO negotiationConfigSaveDTO) {
        // 参数校验
        if (null == negotiationConfigSaveDTO || null == negotiationConfigSaveDTO.getNegotiationName()) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), "协商配置名称为空");
        }

        // 获取当前用户的主体
        UserInfo currentUser = AuthUtil.getCurrentUser();
        if (null == currentUser.getEmployeeId()) {
            return SingleResponse.failure(ResponseCodeEnum.NOT_LOGGED.getCode(), ResponseCodeEnum.NOT_LOGGED.getMsg());
        }

        FlwProcess flwProcess = flwProcessMapper.selectById(negotiationConfigSaveDTO.getProcessId());
        if (null == flwProcess) {
            return SingleResponse.failure(ResponseCodeEnum.DATA_NOT_FOUND.getCode(), "流程定义不存在");
        }

        // 检查协商配置名称是否重复
        LambdaQueryWrapper<ContractNegotiationConfigEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ContractNegotiationConfigEntity::getNegotiationName, negotiationConfigSaveDTO.getNegotiationName());
        long count = this.count(queryWrapper);
        if (count > 0) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), "协商配置名称已存在");
        }
//        List<Long> departmentIds = negotiationConfigSaveDTO.getDepartment();
//        if (CollectionUtils.isEmpty(departmentIds)){
//            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), ResponseCodeEnum.PARAMETER_ERROR.getMsg());
//        }
//        Map<String, List<SysDepartment>> tenantMap = sysDepartmentMapper.selectList(Wrappers.<SysDepartment>lambdaQuery()
//                        .in(SysDepartment::getId, departmentIds)
//                        .select(SysDepartment::getId, SysDepartment::getSysTenantKey))
//                .stream().collect(Collectors.groupingBy(SysDepartment::getSysTenantKey));

//        tenantMap.forEach((sysTenantKey, departmentList) -> {
//            if (CollectionUtils.isEmpty(departmentList)){
//                return;
//            }
        ContractNegotiationConfigEntity configEntity = new ContractNegotiationConfigEntity();
        configEntity.setNegotiationName(negotiationConfigSaveDTO.getNegotiationName());
        configEntity.setProcessKey(flwProcess.getProcessKey());
        configEntity.setPriority(negotiationConfigSaveDTO.getPriority());
//            configEntity.setSysTenantKey(sysTenantKey);
        configEntity.setIsEnabled(true); // 默认启用
        configEntity.setIsPublished(false); // 默认未发布
        this.save(configEntity);

        // 保存合同类型表
        if (!CollectionUtils.isEmpty(negotiationConfigSaveDTO.getScope())) {
            List<ContractNegotiationConfigType> configTypes = new ArrayList<>();
            for (Integer contractTypeId : negotiationConfigSaveDTO.getScope()) {
                ContractNegotiationConfigType configType = new ContractNegotiationConfigType();
                configType.setNegotiationConfigId(configEntity.getId());
                configType.setContractTypeId(contractTypeId);

                contractNegotiationConfigTypeMapper.insert(configType);
            }
        }

//            if (!CollectionUtils.isEmpty(departmentList)) {
//                for (SysDepartment dept : departmentList) {
//                    ContractNegotiationDepartment department = new ContractNegotiationDepartment();
//                    department.setDepartmentId(dept.getId());
//                    department.setNegotiationConfigId(configEntity.getId());
//                    contractNegotiationDepartmentMapper.insert(department);
//                }
//            }
//        });
        return SingleResponse.success();
    }


    /**
     * 构造展示结果
     *
     * @param id
     * @return
     */
    public NegotiationConfigShowDTO buildResult(Long id) {
        // 创建返回值对象
        NegotiationConfigShowDTO result = new NegotiationConfigShowDTO();
        // 查询协商配置信息
        ContractNegotiationConfigEntity negotiationConfig = this.getById(id);
        if (negotiationConfig == null) {
            return result;
        }

        FlwProcess flwProcess = null;
        String processKey = negotiationConfig.getProcessKey();
        if (processKey != null && !processKey.trim().isEmpty()) {
            flwProcess = flwProcessMapper.selectOne(Wrappers.<FlwProcess>lambdaQuery()
                    .eq(FlwProcess::getProcessKey, processKey)
                    .orderByDesc(FlwProcess::getProcessVersion)
                    .last("limit 1"));
        }

        // 查询协商配置合同类型
        List<Integer> typeIds = contractNegotiationConfigTypeMapper.selectList(new LambdaQueryWrapper<ContractNegotiationConfigType>()
                        .eq(ContractNegotiationConfigType::getNegotiationConfigId, id)
                        .select(ContractNegotiationConfigType::getContractTypeId))
                .stream()
                .filter(Objects::nonNull)
                .map(ContractNegotiationConfigType::getContractTypeId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

//        String typeScope = "";
//        if (!CollectionUtils.isEmpty(typeIds)) {
//            typeScope = contractTypeMapper.selectList(new LambdaQueryWrapper<ContractTypeEntity>()
//                            .in(ContractTypeEntity::getId, typeIds)
//                            .select(ContractTypeEntity::getId, ContractTypeEntity::getTypeName))
//                    .stream().map(ContractTypeEntity::getTypeName).collect(Collectors.joining(","));
//        }

//        List<Long> departmentIds = contractNegotiationDepartmentMapper.selectList(new LambdaQueryWrapper<ContractNegotiationDepartment>()
//                        .eq(ContractNegotiationDepartment::getNegotiationConfigId, id))
//                .stream().map(ContractNegotiationDepartment::getDepartmentId).collect(Collectors.toList());

        // 构造结果
        result.setId(negotiationConfig.getId());
        result.setNegotiationName(negotiationConfig.getNegotiationName());
        result.setScope(typeIds);
//        result.setDepartment(departmentIds);
        if (flwProcess != null) {
            result.setProcessId(flwProcess.getId());
        }
        result.setPriority(negotiationConfig.getPriority());

        // 返回结果
        return result;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public SingleResponse updateNegotiationConfig(NegotiationConfigUpdateDTO negotiationConfigUpdateDTO) {
        // 参数校验
        if (null == negotiationConfigUpdateDTO || null == negotiationConfigUpdateDTO.getId() || null == negotiationConfigUpdateDTO.getNegotiationName()) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), "协商配置ID和名称不能为空");
        }

        // 获取当前用户的主体
        UserInfo currentUser = AuthUtil.getCurrentUser();
        if (null == currentUser.getEmployeeId()) {
            return SingleResponse.failure(ResponseCodeEnum.NOT_LOGGED.getCode(), ResponseCodeEnum.NOT_LOGGED.getMsg());
        }

        FlwProcess flwProcess = flwProcessMapper.selectById(negotiationConfigUpdateDTO.getProcessId());
        if (null == flwProcess) {
            return SingleResponse.failure(ResponseCodeEnum.DATA_NOT_FOUND.getCode(), "流程定义不存在");
        }

        // 检查记录是否存在
        ContractNegotiationConfigEntity existConfig = this.getById(negotiationConfigUpdateDTO.getId());
        if (null == existConfig) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), "协商配置不存在");
        }

        // 检查协商配置名称是否重复（排除当前记录）
        LambdaQueryWrapper<ContractNegotiationConfigEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ContractNegotiationConfigEntity::getNegotiationName, negotiationConfigUpdateDTO.getNegotiationName())
                .ne(ContractNegotiationConfigEntity::getId, negotiationConfigUpdateDTO.getId());
        long count = this.count(queryWrapper);
        if (count > 0) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), "协商配置名称已存在");
        }

        // 更新主表
        existConfig.setNegotiationName(negotiationConfigUpdateDTO.getNegotiationName());
        existConfig.setProcessKey(flwProcess.getProcessKey());
        existConfig.setPriority(negotiationConfigUpdateDTO.getPriority());

        this.updateById(existConfig);

        // 更新合同类型表 - 先删除旧的关联关系
        contractNegotiationConfigTypeMapper.delete(
                new LambdaQueryWrapper<ContractNegotiationConfigType>()
                        .eq(ContractNegotiationConfigType::getNegotiationConfigId, negotiationConfigUpdateDTO.getId())
        );

        // 插入新的关联关系
        if (!CollectionUtils.isEmpty(negotiationConfigUpdateDTO.getScope())) {
            for (Integer contractTypeId : negotiationConfigUpdateDTO.getScope()) {
                ContractNegotiationConfigType configType = new ContractNegotiationConfigType();
                configType.setNegotiationConfigId(negotiationConfigUpdateDTO.getId());
                configType.setContractTypeId(contractTypeId);
                contractNegotiationConfigTypeMapper.insert(configType);
            }
        }

//        // 更新部门表 - 先删除旧的关联关系
//        contractNegotiationDepartmentMapper.delete(Wrappers.<ContractNegotiationDepartment>lambdaQuery()
//                .eq(ContractNegotiationDepartment::getNegotiationConfigId, existConfig.getId()));
//        if (!CollectionUtils.isEmpty(negotiationConfigUpdateDTO.getDepartment())) {
//            List<ContractNegotiationDepartment> departments = negotiationConfigUpdateDTO.getDepartment().stream().map(item -> {
//                ContractNegotiationDepartment negotiationDepartment = new ContractNegotiationDepartment();
//                negotiationDepartment.setNegotiationConfigId(existConfig.getId());
//                negotiationDepartment.setDepartmentId(item);
//                return negotiationDepartment;
//            }).collect(Collectors.toList());
//            contractNegotiationDepartmentMapper.insert(departments);
//        }

        return SingleResponse.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SingleResponse deleteNegotiationConfig(Long id) {
        // 参数校验
        if (null == id) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), "协商配置ID不能为空");
        }

        // 检查记录是否存在
        ContractNegotiationConfigEntity existConfig = this.getById(id);
        if (null == existConfig) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), "协商配置不存在");
        }

        // 检查是否已发布，已发布的配置不能删除
        if (existConfig.getIsEnabled()) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), "已启用的协商配置不能删除");
        }

        // 删除关联的合同类型关系
        contractNegotiationConfigTypeMapper.delete(
                new LambdaQueryWrapper<ContractNegotiationConfigType>()
                        .eq(ContractNegotiationConfigType::getNegotiationConfigId, id)
        );

//        contractNegotiationDepartmentMapper.delete(
//                new LambdaQueryWrapper<ContractNegotiationDepartment>()
//                        .eq(ContractNegotiationDepartment::getNegotiationConfigId, id)
//        );

        // 删除主记录
        boolean deleteResult = this.removeById(id);
        if (!deleteResult) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), "删除协商配置失败");
        }

        return SingleResponse.success();
    }

    @Override
    public SingleResponse<NegotiationConfigShowDTO> getNegotiationConfig(Long id) {
        return SingleResponse.of(this.buildResult(id));
    }

    @Override
    public SingleResponse updateStatus(Long id) {
        if (null == id) {
            return SingleResponse.failure(ResponseCodeEnum.PARAMETER_ERROR.getCode(), "参数错误");
        }
        ContractNegotiationConfigEntity config = this.getById(id);
        if (null == config) {
            return SingleResponse.failure(ResponseCodeEnum.DATA_NOT_FOUND.getCode(), ResponseCodeEnum.DATA_NOT_FOUND.getMsg());
        }
        config.setIsEnabled(!config.getIsEnabled());
        this.updateById(config);
        return SingleResponse.success();
    }

    @Override
    public Long selectOptimalNegotiationProcessId(Integer contractTypeId, Long applicantDepartmentId) {
        if (contractTypeId == null) {
            return null;
        }

        try {
            log.info("协商流程匹配 - 只根据合同类型匹配，不考虑部门。合同类型ID: {}", contractTypeId);

            // 1. 查找支持该合同类型的所有协商配置
            List<ContractNegotiationConfigType> configTypes = contractNegotiationConfigTypeMapper.selectList(
                    new LambdaQueryWrapper<ContractNegotiationConfigType>()
                            .eq(ContractNegotiationConfigType::getContractTypeId, contractTypeId)
            );

            if (configTypes.isEmpty()) {
                log.info("未找到合同类型对应的协商配置，合同类型ID: {}", contractTypeId);
                return null;
            }

            final List<Long> candidateConfigIds = configTypes.stream()
                    .map(ContractNegotiationConfigType::getNegotiationConfigId)
                    .distinct()
                    .collect(Collectors.toList());

            log.info("找到 {} 个候选协商配置ID: {}", candidateConfigIds.size(), candidateConfigIds);

            // 2. 查询这些配置的详细信息，只考虑已启用的，并按优先级排序
            final List<ContractNegotiationConfigEntity> candidateConfigs = this.listByIds(candidateConfigIds)
                    .stream()
                    .filter(config -> Boolean.TRUE.equals(config.getIsEnabled()))
                    .sorted((c1, c2) -> {
                        // 按优先级降序排序（优先级高的在前）
                        int priorityCompare = Integer.compare(
                                c2.getPriority() != null ? c2.getPriority() : 0,
                                c1.getPriority() != null ? c1.getPriority() : 0
                        );
                        if (priorityCompare != 0) {
                            return priorityCompare;
                        }
                        // 如果优先级相同，按ID降序排序
                        return Long.compare(c2.getId(), c1.getId());
                    })
                    .collect(Collectors.toList());

            if (candidateConfigs.isEmpty()) {
                log.warn("没有已启用的协商配置，合同类型ID: {}", contractTypeId);
                return null;
            }

            // 3. 直接选择优先级最高的配置（已经按优先级排序，不再考虑部门匹配）
            ContractNegotiationConfigEntity optimalConfig = candidateConfigs.get(0);
            log.info("选择协商配置: ID={}, 名称={}, 优先级={}, ProcessKey={}",
                    optimalConfig.getId(), optimalConfig.getNegotiationName(),
                    optimalConfig.getPriority(), optimalConfig.getProcessKey());

            // 4. 根据流程Key查找对应的流程定义
            String processKey = optimalConfig.getProcessKey();
            FlwProcess flwProcess = flwProcessMapper.selectOne(Wrappers.<FlwProcess>lambdaQuery()
                    .eq(FlwProcess::getProcessKey, processKey)
                    .ne(FlwProcess::getProcessState, 0)
                    .orderByDesc(FlwProcess::getProcessVersion)
                    .last("limit 1"));

            if (null != flwProcess) {
                log.info("成功匹配协商流程，合同类型ID: {}, 选择的流程ID: {}, 配置ID: {}, 优先级: {}",
                        contractTypeId, flwProcess.getId(), optimalConfig.getId(), optimalConfig.getPriority());
                return flwProcess.getId();
            } else {
                log.warn("未找到对应的流程定义，processKey: {}", processKey);
                return null;
            }

        } catch (Exception e) {
            log.error("协商流程匹配失败，合同类型ID: {}", contractTypeId, e);
            return null;
        }
    }

}
